import json, os
import zipfile as zip

def replace_text(text: str):
    global data, data1, data2, name, file
    if (text == ''):
        return ''
    text = text.replace("%s", '`')
    arr = list(text)
    num = 1
    for i in range(len(arr)): 
        if arr[i] == '`':
            arr[i] = f'%{num}$s'
            num += 1
    return ''.join(arr)

def output():
    global data, data1, data2, name, file, merged_data, merged_value, head_all, jp_yes, res
    with open('res/' + res + '/assets/minecraft/lang/' + name + '.json', 'w', encoding='utf-8') as outfile:
        json.dump(merged_data, outfile, ensure_ascii=False, indent=4, sort_keys=True)
        
def files(f_file):
    global data, data1, data2, name, file
    with open(f_file + '.json', 'r', encoding='utf-8') as file1:
        data1 = json.load(file1)

    with open(file + '.json', 'r', encoding='utf-8') as file2:
        data2 = json.load(file2)
        
    data = set(data1.keys()) | set(data2.keys())

def all():
    global data, data1, data2, name, file, merged_data, merged_value, head_all, jp_yes
    name = name + '_all'
    for key in data:
        d1 = replace_text(data1.get(key, ""))
        d2 = replace_text(data2.get(key, ""))
        if (d1 != d2 and key not in head_all):
            value1 = d1
            value2 = d2
            if (key in jp_yes):
                value2 = data2.get(key, "")
            # 拼接值，去除多余的空格
            merged_value = " | ".join([v for v in [value1, value2] if v])
        else :
            merged_value = d1
            
        merged_data[key] = merged_value
        
    output()

def part():
    '''
    该部分会对以下内容进行双语翻译：
        进度
        群系
        方块
        魔咒
        物品
        实体
        物品类别
        唱片
        物品属性
        颜色
        命令提示
        UI提示
        死亡信息
        药水效果
        背景音乐
    '''
    global data, data1, data2, name, file, merged_data, merged_value, head_all, jp_yes
    # 合并两个 JSON 文件的内容
    head_in = ["advancements", "biome", "block", "enchantment", "entity", "item", "itemGroup", "jukebox_song", "subtitles", "trim_material", "trim_pattern", "instrument", "attribute", "color", "commands", "container", "death", "effect", "music", "upgrade", "command"]
    head_all_in = ["filled_map.buried_treasure", "filled_map.explorer_jungle", "filled_map.explorer_swamp", "filled_map.mansion", "filled_map.monument", "filled_map.trial_chambers", "filled_map.village_desert", "filled_map.village_plains", "filled_map.village_savanna", "filled_map.village_snowy", "filled_map.village_taiga", "gameMode.changed", 'attribute.modifier.equals.1', 'attribute.modifier.equals.2', 'attribute.modifier.plus.0', 'attribute.modifier.plus.1', 'attribute.modifier.plus.2', 'attribute.modifier.take.0', 'attribute.modifier.take.1']
    # head_all_not = [""]
    for key in data:
        # 查找点的位置
        dot_index = key.find('.')
        
        # 如果存在点，则提取点之前的部分作为前缀；否则整个路径作为前缀
        prefix = key[:dot_index] if dot_index != -1 else key
        d1 = replace_text(data1.get(key, ""))
        d2 = replace_text(data2.get(key, ""))
        if ((prefix in head_in or key in head_all_in)
            and d1 != d2 
            and key not in head_all
            # and key not in head_all_not
            ):
            value1 = d1
            value2 = d2
            if (key in jp_yes):
                value2 = data2.get(key, "")
            # 拼接值，去除多余的空格
            merged_value = " | ".join([v for v in [value1, value2] if v])
        else :
            merged_value = d1
        
        merged_data[key] = merged_value
        
    output()

def zips(s_path, o_path):
    if not os.path.isdir(s_path):
        raise FileNotFoundError(f"源路径不存在或不是目录: {s_path}")
    with zip.ZipFile(o_path, 'w') as zipf :
        for root, dirs, files in os.walk(s_path):
            for file in files:
                zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), s_path))

# 初始值
merged_data = {}
merged_value = ''
head_all = ['commands.scoreboard.players.list.entity.entry', 'gui.abuseReport.reason.narration', 'options.generic_value', 'options.percent_add_value', 'options.percent_value', 'options.pixel_value', 'commands.list.nameAndId', 'mco.upload.entry.id', 'pack.nameAndSource', 'potion.withDuration', 'painting.dimensions', 'potion.withDuration', 'item.minecraft.firework_rocket.multiple_stars', 'container.shulkerBox.itemCount', 'chat.type.admin', 'debug.gamemodes.press_f4', 'gui.multiLineEditBox.character_limit', 'gui.recipebook.page', 'item.minecraft.bundle.fullness', 'mco.upload.entry.cheats', 'mco.upload.entry.commands', 'multiplayer.status.player_count', 'advancements.progress']
jp_yes = ['commands.test.summary.all_required_passed', 'advancements.sad_label', 'commands.test.summary.failed', 'optimizeWorld.stage.failed']

data1, data2 = '', ''
data = ''
name = 'cn_gb'
file = '英式英文'
files('中文')
res = '§l中英双语包§a(全部翻译)'

all()
print("合并完成")

data1, data2 = '', ''
data = ''
name = 'cn_gb'
file = '英式英文'
res = '§l中英双语包§c(部分翻译)'

part()
print("合并完成")

name = 'cn_jp'
file = '日文'
files('中文')
res = '§l中日双语包§a(全部翻译)'

all()
print("合并完成")

name = 'cn_jp'
file = '日文'
files('中文')
res = '§l中日双语包§c(部分翻译)'

part()
print("合并完成")

name = 'cn_gb_jp'
file = '日文'
files('res/§l中英双语包§a(全部翻译)/assets/minecraft/lang/cn_gb_all')
res = '§l中英日三语包§a(全部翻译)'

all()
print("合并完成")

zips('res/§l中英双语包§a(全部翻译)/', 'output/§l中英双语包§a(全部翻译).zip')
zips('res/§l中日双语包§a(全部翻译)/', 'output/§l中日双语包§a(全部翻译).zip')
zips('res/§l中英双语包§c(部分翻译)/', 'output/§l中英双语包§c(部分翻译).zip')
zips('res/§l中日双语包§c(部分翻译)/', 'output/§l中日双语包§c(部分翻译).zip')
zips('res/§l中英日三语包§a(全部翻译)/', 'output/§l中英日三语包§a(全部翻译).zip')
print("压缩完成")